package com.socool.sinofaith.ui;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.socool.sinofaith.R;
import com.socool.sinofaith.SocoolApplication;
import com.socool.sinofaith.adapter.CurrentTaskAdapter;
import com.socool.sinofaith.adapter.RuningTaskAdapter;
import com.socool.sinofaith.dao.QuestionAnswerDao;
import com.socool.sinofaith.dao.SifTaskAddressDao;
import com.socool.sinofaith.dao.SifTaskDao;
import com.socool.sinofaith.model.SifTaskAddressBean;
import com.socool.sinofaith.model.SifTaskBean;
import com.socool.sinofaith.model.Task;
import com.socool.sinofaith.view.LoadingDialog;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class RuningTaskFragment extends Fragment {

	private PullToRefreshListView mPullRefreshListView;
	private ListView listView;
	private RuningTaskAdapter mCurrentTaskAdapter;
	public int currentIndex = 1;
	private LoadingDialog mLoadingDialog;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_currenttask, null);
		SocoolApplication.addActivity(this.getActivity());
		mPullRefreshListView = (PullToRefreshListView) view
				.findViewById(R.id.listview);
		return view;

	}

	void init() {
		mLoadingDialog = new LoadingDialog(this.getActivity());
		listView = mPullRefreshListView.getRefreshableView();
		mCurrentTaskAdapter = new RuningTaskAdapter(this.getActivity(),
				listView);
		listView.setAdapter(mCurrentTaskAdapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				Intent intent = new Intent(RuningTaskFragment.this
						.getActivity(), TaskDetailActivity.class);
				intent.putExtra("task",
						mCurrentTaskAdapter.getMdatas().get(arg2 - 1));
				SifTaskDao dao = new SifTaskDao(getActivity());
				ArrayList<SifTaskBean> query = dao.query(mCurrentTaskAdapter
						.getMdatas().get(arg2 - 1).getTask_ID());
				if (query.size() > 0)
					RuningTaskFragment.this.getActivity().startActivity(intent);
				else
					Toast.makeText(getActivity(), "数据错误,请重新下拉刷新", 1).show();

			}
		});

		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						String label = DateUtils.formatDateTime(
								RuningTaskFragment.this.getActivity(),
								System.currentTimeMillis(),
								DateUtils.FORMAT_SHOW_TIME
										| DateUtils.FORMAT_SHOW_DATE
										| DateUtils.FORMAT_ABBREV_ALL);

						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);

						// 清空数据重新请求
						mCurrentTaskAdapter.getMdatas().clear();
						currentIndex = 1;
						getData();
					}
				});
		mPullRefreshListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
					@Override
					public void onLastItemVisible() {
						// lastLoadingView.setVisibility(View.VISIBLE);
						currentIndex++;
						getData();
					}
				});

		getData();
	}

	@Override
	public void onResume() {
		init();
		super.onResume();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		MainActivity.imageview.setVisibility(View.VISIBLE);
		MainActivity.imageview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// 清空数据重新请求
				mCurrentTaskAdapter.getMdatas().clear();
				currentIndex = 1;
				getData();
			}
		});
		super.onActivityCreated(savedInstanceState);
	}

	void getData() {
		new AsyncTask<Void, Void, ArrayList<Task>>() {

			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				mLoadingDialog.show();
			}

			@Override
			protected ArrayList<Task> doInBackground(Void... arg0) {
				QuestionAnswerDao mQuestionAnswerDao = new QuestionAnswerDao(
						RuningTaskFragment.this.getActivity());
				// String taskIdSet = mQuestionAnswerDao.queryTaskIdSet();
				SifTaskDao sifTaskDao = new SifTaskDao(
						RuningTaskFragment.this.getActivity());
				SifTaskAddressDao sifTaskAddressDao = new SifTaskAddressDao(
						RuningTaskFragment.this.getActivity());
				ArrayList<Task> sifTaskBeanList = new ArrayList<Task>();
				ArrayList<SifTaskBean> list = sifTaskDao
						.querySifTaskBean(currentIndex);
				if (list != null) {
					for (int i = 0; i < list.size(); i++) {
						SifTaskBean sifTaskBean = list.get(i);
						Task task = new Task();
						task.setEndTM(sifTaskBean.getEndTM());
						task.setIsPublic(sifTaskBean.getIsPublic());
						task.setIsPush(sifTaskBean.getIsPush());
						task.setStartTM(sifTaskBean.getStartTM());
						task.setTask_ID(sifTaskBean.getTask_ID());
						task.setTaskDesc(sifTaskBean.getTaskDesc());
						task.setGetTaskTime("0");
						task.setTaskName(sifTaskBean.getTaskName());
						task.setTaskAddress(sifTaskAddressDao
								.queryBySql("select * from "
										+ SifTaskAddressBean.TABLENAME
										+ " where Task_ID="
										+ sifTaskBean.getTask_ID()));
						sifTaskBeanList.add(task);
					}

				}
				// Iterator<String> iterator = taskIdSet.iterator();
				// while (iterator.hasNext()) {
				// String taskid = iterator.next();
				//
				// }
				return sifTaskBeanList;
			}

			@Override
			protected void onPostExecute(ArrayList<Task> result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				if (result != null && result.size() > 0) {
					mCurrentTaskAdapter.addDatas(result);
					mCurrentTaskAdapter.notifyDataSetChanged();
					// } else {
					//
					// Toast.makeText(RuningTaskFragment.this.getActivity(),
					// "暂无进行中的任务！", Toast.LENGTH_SHORT).show();
				}
				mLoadingDialog.dismiss();
				mPullRefreshListView.onRefreshComplete();
			}

		}.execute();
	}
}
